import React, { useState, useEffect } from 'react'
import { Table, Card, Button, Modal, Form, Input, Space, message } from 'antd'
const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 }
}

const UserList = () => {
  const [List, setList] = useState([])
  const [visible, setVisible] = useState(false)
  const [form] = Form.useForm()
  const columns = [
    {
      title: '账号',
      dataIndex: 'Account',
      key: 'Account',
    },
    {
      title: '姓名',
      dataIndex: 'Name',
      key: 'Name',
    },
    {
      title: '备注',
      dataIndex: 'Remark',
      key: 'Remark',
    },
    {
      title: '操作',
      key: 'Handle',
      render: (text, record) => (
        <Space size="middle">
          <Button type="link" onClick={() => deleteItem(record)}>删除</Button>
        </Space>
      )
    }
  ]

  useEffect(() => {
    init()
  }, [])

  const init = async() => {
    document.title = '用户列表'
    setList([
      {
        key: 1,
        Account: 'admin',
        Name: '管理员',
        Remark: '管理员账号'
      },
      {
        key: 2,
        Account: '18888888888',
        Name: '程斌',
        Remark: '程斌使用'
      }
    ])
  }

  const submitForm = async() => {
    let values = await form.validateFields()
    form.resetFields()
    const same = List.find(v => v.Account === values.Account)
    if (same) {
      message.error('已有此账号')
      return
    }
    console.log(values)
    setVisible(false)
  }

  const deleteItem = async(item) => {
    console.log(item)
  }

  return (
    <div className="user-list">
      <Card bordered={false}>
        <div className="flex flex-between">
          <Button type="primary" onClick={() => setVisible(true)}>添加用户</Button>
        </div>
      </Card>
      <Card bordered={false}>
        <Table dataSource={List} columns={columns} scroll={{ y: 360 }} />
      </Card>
      <Modal
        visible={visible}
        title="添加账号信息"
        okText="提交"
        onCancel={() => setVisible(false)}
        onOk={submitForm}
      >
        <Form
          {...layout}
          form={form}
          name="basic"
          initialValues={{ modifier: 'public' }}
        >
          <Form.Item
            label="账号"
            name="Account"
            rules={[{ required: true, message: '请输入账号' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="姓名"
            name="Name"
            rules={[{ required: true, message: '请输入姓名' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="备注"
            name="Remark"
            rules={[{ required: true, message: '请输入备注' }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default UserList